package com.jastar.android.game.richman;

import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import com.jastar.android.game.richman.logic.GameManager;
import com.jastar.android.game.richman.logic.GameView;
import com.jastar.android.game.richman.logic.bean.Cell;
import com.jastar.android.game.richman.logic.bean.Player;
import com.jastar.android.game.richman.logic.card.Card;
import com.jastar.android.test.R;
import com.jastar.android.util.Alert;
import com.jastar.android.util.Utils;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

public class GameActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String NAME_PLAYER_COUNT = "playerCount";
    public static final String NAME_MONEY = "money";
    private GameView gameView;
    private ImageButton btnRoll;
    private TextView tvStatus;
    private LinearLayout layoutInfo;

    private final Map<String, TextView> playerInfos = new HashMap<>();
    private GameManager manager;
    private int lineCount; //每行/列格子数

    public GameManager getManager() {
        return manager;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_richman_game);

        // BaiduTTSManager.initInstance(this);

        int playerCount = getIntent().getIntExtra(NAME_PLAYER_COUNT, 2);
        int money = getIntent().getIntExtra(NAME_MONEY, 10);

        gameView = findViewById(R.id.game_view);
        btnRoll = findViewById(R.id.btn_roll);
        tvStatus = findViewById(R.id.tv_status);
        layoutInfo = findViewById(R.id.layout_info);

        manager = gameView.initManager(this, playerCount, money);
        lineCount = (manager.getLineAverage() + 1);

        resetViewsSize();       //设置各个控件尺寸
        loadAllPlayerPic();     //预加载角色图片
        initPlayerInfoViews();  //动态添加角色信息控件
        updateStatus(manager.getCurrentPlayer());

        btnRoll.setOnClickListener(this);
    }

    private void resetViewsSize() {
        Point size = Utils.getActivityDisplaySize(this);

        ViewGroup.LayoutParams params = gameView.getLayoutParams();
        params.width = size.x;
        params.height = size.y;
        gameView.setLayoutParams(params);

        setMargin(btnRoll, 0, -size.y / 3);
        setMargin(tvStatus, 0, -size.y / 3 - 80);
        setMargin(layoutInfo, size.x / lineCount, size.y / lineCount);

    }

    private View setMargin(View view, int left, int top) {
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        params.leftMargin = left;
        params.topMargin = top;
        view.setLayoutParams(params);
        return view;
    }

    private void loadAllPlayerPic() {
        int h = gameView.getLayoutParams().height / lineCount;
        manager.getPlayers().forEach(p -> p.loadBitmap(getResources(), h));
    }

    /**
     * 这里使用的完全动态创建
     * 还有另一种半动态的方式，预先创建组件的XML文件，然后使用以下代码加载进来：
     * View view = LayoutInflater.from(this).inflate(R.layout.XML文件名, null);
     */
    private void initPlayerInfoViews() {
        GridLayout layout = new GridLayout(this);
        layout.setRowCount(3);
        layout.setColumnCount(2);

        manager.getPlayers().forEach(player -> {
            Bitmap bitmap = player.getThumbnailBitmap();
            int w = bitmap.getWidth() * 2 / 3, h = bitmap.getHeight() * 2 / 3;

            ImageView image = new ImageView(this);
            image.setLayoutParams(new GridLayout.LayoutParams(new ViewGroup.LayoutParams(w, h)));
            image.setImageBitmap(bitmap);

            TextView tv = new TextView(this);
            tv.setLayoutParams(new GridLayout.LayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, h)));
            tv.setGravity(Gravity.CENTER_VERTICAL);
            tv.setText(String.valueOf(player.getMoney()));
            tv.setTextColor(player.getColor());
            tv.setTextSize(18F);

            layout.addView(setMargin(image, 10, 0));
            layout.addView(setMargin(tv, 20, 0));
            playerInfos.put(player.getName(), tv);
        });
        layoutInfo.addView(layout);
    }

    private void updateStatus(Player currentPlayer) {
        btnRoll.setImageBitmap(currentPlayer.getThumbnailBitmap());
        manager.getPlayers().forEach(p -> playerInfos.get(p.getName()).setText(p.getMoney() + ""));
    }

    @Override
    public void onClick(View v) {
        btnRoll.setEnabled(false);
        Player p = manager.getCurrentPlayer();
        Cell place = manager.getCells().get(p.getPosition());
        List<Card> cards = p.getCards();
        if (null != cards && !cards.isEmpty()) {
            String[] texts = Stream.concat(cards.stream().map(Card::getMessage), Stream.of("不使用")).toArray(String[]::new);
            Alert.select(this, p.getIcon(), "请选择使用的卡片：", (d, w) -> {
                if (w < cards.size()) {
                    Card card = cards.remove(w);
                    card.use(this, place, p, () -> roll(p));
                } else { //最后一个选项是不使用
                    roll(p);
                }
            }, texts);
        } else {
            roll(p);
        }
    }

    private void roll(Player p) {
        manager.rollDice(result -> {
            manager.moveCurrentPlayer(result);
            Cell c = manager.getCells().get(p.getPosition());

            c.hand(this, p, () -> {

                if (p.getMoney() < 0) {
                    Alert.info(this, p.getIcon(), "现金不足，随机变卖房产!", (d1, w1) -> {
                        boolean res = manager.randomSale(p);
                        if (!res) {
                            Alert.info(this, p.getIcon(), "房产不足，破产!", (d2, w2) -> {
                                playerInfos.get(p.getName()).setText("破产");
                                removeCurrentPlayer();//移除掉会自动切换下一个

                                if (manager.getPlayers().size() <= 1) gameOver();
                            });
                        } else {
                            changeNextPlayer();
                        }
                    });
                } else {
                    changeNextPlayer();
                }

            });
        });
    }

    private void removeCurrentPlayer() {
        manager.removeCurrentPlayer();
        updateStatus(manager.getCurrentPlayer());
        btnRoll.setEnabled(true);
    }

    private void changeNextPlayer() {
        manager.changeNextPlayer();
        updateStatus(manager.getCurrentPlayer());
        btnRoll.setEnabled(true);
    }

    private void gameOver() {
        btnRoll.setEnabled(false);
        Player cp = manager.getCurrentPlayer();
        tvStatus.setTextColor(cp.getColor());
        tvStatus.setText(MessageFormat.format("{0}胜利，剩余金额：{1}", cp.getName(), cp.getMoney()));
    }

}